#pragma once
/*日志*/

/*日志等级*/
#define DEBUG 0
#define NORMAL 1
#define WARNING 2
#define ERROR 3
#define FATAL 4
#include <string>
#include <iostream>
#include <time.h>
#include <stdarg.h>

/*level->string*/
std::string getLevelStr(int level)
{
    if (level == DEBUG)
        return "DEBUG";
    else if (level == NORMAL)
        return "NORMAL";
    else if (level == WARNING)
        return "WARNING";
    else if (level == ERROR)
        return "ERROR";
    else if (level == FATAL)
        return "FATAL";
}

/*获取日志正文*/
void setTextMessage(int level, std::string &out)
{
    char textBuffer[1024]; /*[level][time]*/
    std::string leverStr = getLevelStr(level);
    time_t timeP = time(nullptr);       /*获得时间戳*/
    struct tm *pTm = localtime(&timeP); /*时间戳转化*/
    snprintf(textBuffer, sizeof(textBuffer), "[%s][%d.%d.%d--%d:%d:%d]", leverStr.c_str(),
             pTm->tm_year + 1900, pTm->tm_mon + 1, pTm->tm_wday, pTm->tm_hour, pTm->tm_min, pTm->tm_sec);
    out = textBuffer;
}

void setFormatMessage(va_list &ap,const char * &format,std::string &out)
{
    char formatBuffer[1024];
    int n = vsnprintf(formatBuffer,sizeof(formatBuffer),format,ap);
    if(n > 0)
    {
        formatBuffer[n] = 0;
        out = formatBuffer;
    }
}

void logMessage(int level, const char *format, ...)
{
    std::string textMessage;
    std::string formatMessage;
    setTextMessage(level, textMessage);

    va_list arg;
    va_start(arg,format);
    setFormatMessage(arg,format,formatMessage);

    std::cout << textMessage << formatMessage << std::endl;
}